﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ebc.componentbinder
{
    class Injector
    {
        private Delegate messageProcessor;
        private Action<object> listener;


        public static Injector Intercept(Delegate messageProcessor)
        {
            return new Injector { messageProcessor = messageProcessor };
        }


        public Delegate WithListener(Action<object> listener)
        {
            this.listener = listener;

            return Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(this.messageProcessor.Method.GetParameters()[0].ParameterType),
                                           this,
                                           this.GetType().GetMethod("ListenAndPassOn", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic),
                                           false);
        }


        void ListenAndPassOn(object message)
        {
            this.listener(message);
            this.messageProcessor.DynamicInvoke(message);
        }
    }
}
